package deepbitview

/**
 * a very simple trading bot, which can only handle one order at a time
 */
class MtgoxTradingBotService {

    MtgoxService mtgoxService

    TickerService tickerService

    static transactional = true

    /**
     * are there any active orders currently
     * @return
     */
    boolean hasActiveOrders() {
        def value = mtgoxService.listOpenOrders();

        log.debug("recieved values for orders: ${value}")
        if (value == false) {
            return false
        }
        else if (value.size() == 0) {
            return false
        }
        else {
            return true
        }
    }

    /**
     * initializes an relative order set, based on the last known price
     */
    boolean intializeRelativeOrderSet(double margin, double currentMarketPrice = tickerService.fetchLatestUSDExchangeRate(), boolean submit = true) {
        double value = margin / 100 * currentMarketPrice

        initializeAbsoluteOrderSet(value, currentMarketPrice, submit)

    }

/**
 * initializes an absolute order set, based on the large known price
 * @param margin
 */
    boolean initializeAbsoluteOrderSet(double margin, double currentMarketPrice = tickerService.fetchLatestUSDExchangeRate(), boolean submit = true) {

        if (hasActiveOrders()) {
            log.debug "sorry, currently there are orders active already"
            return false
        }
        else {

            log.debug("current market price: ${currentMarketPrice} and margin is: ${margin}")

            double buyValue = currentMarketPrice - margin
            double sellValue = currentMarketPrice + margin
            double buyAmount = Double.parseDouble(mtgoxService.getCurrentBalance().usd) / currentMarketPrice
            double sellAmount = Double.parseDouble(mtgoxService.getCurrentBalance().coins) + buyAmount

            log.debug "we are going to buy ${buyAmount} coins at ${buyValue} and sell ${sellAmount} at ${sellValue}"

            BotOrder order = new BotOrder()

            order.orderDate = new Date()
            order.buyingPrice = buyValue
            order.sellingPrice = sellValue
            order.marketPrice = currentMarketPrice
            order.buyBitCoins = buyAmount
            order.sellBitCoins = sellAmount
            order.submitted = submit

            if (submit) {
                def sellResult = mtgoxService.placeSellOrder(sellAmount, sellValue)
                def buyResult = mtgoxService.placeBuyOrder(buyAmount, buyValue)

                log.debug("sell: ${sellResult}")
                log.debug("buy: ${buyResult}")

                order.buyOrderOID = buyResult
                order.sellOrderOID = sellResult
            }

            order.save(flush: true)

            return true
        }
    }


}
